﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OVS_FormsRecognition.Manager;
using System.Windows.Controls;
using System.Net.Mail;
using System.Net;
using OVS.BusinessObjects;
using OVS.BLL;
using OVS.DAL;
namespace OVS_NotificationSender.Manager
{
    public class NotificationSenderManager
    {

        #region attributs
       
        #endregion


        /// <summary>
        /// Logger par défaut du ManagerUtilisateurs
        /// </summary>
        private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(typeof(NotificationSenderManager));

        #region Gestion du singleton

        /// <summary>
        /// Instance locale pour héberger le singleton
        /// </summary>
        static NotificationSenderManager instance = null;

        /// <summary>
        /// Objet permettant la gestion des LOCK lors de l'instanciation
        /// </summary>
        static readonly object padlock = new object();

        /// <summary>
        /// Constructeur par défaut
        /// </summary>
        NotificationSenderManager()
        {
            if (_Log.IsDebugEnabled)
                _Log.DebugFormat("Nouvelle instance de '{0}'", this.GetType().ToString());

        }

        /// <summary>
        /// Déclaration unique par gestion du singleton
        /// </summary>
        public static NotificationSenderManager Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new NotificationSenderManager();
                    }
                    return instance;
                }
            }
        }

        #endregion Gestion du singleton

      
        /// <summary>
        /// Registers the event handler.
        /// </summary>
        /// <param name="pSizeCalculationStartEvent">The p size calculation start event.</param>
        public void registerEventHandler()
        {
            FormsRecognitionManager.Instance.NotificationSenderEventStart += new FormsRecognitionManager.NotificationSenderEventHandler(CallBackNotificationSenderEventStart);
        }

        /// <summary>
        /// Calls the back size calculation start event.
        /// </summary>
        /// <param name="nullObject">The null object.</param>
        /// <param name="pSizeCalculationEventArgs">The <see cref="SizeCalculationEventArgs" /> instance containing the event data.</param>
        private void CallBackNotificationSenderEventStart(object nullObject, NotificationSenderEventArgs pSizeCalculationEventArgs)
        {
            _Log.Debug("new event CallBackNotificationSenderEventStart !!!");

            //if (_LabelLastAlertInfo != null)
            //{
            //    _LabelLastAlertInfo.Content = DateTime.Now.ToString();
            //}
            /* 
            */

            Alert currentAlert = AlertBLL.Instance.GetAlert(pSizeCalculationEventArgs.id_alert);
            int userId = 0;
            //recupération de l'utilisateur à qui envoyer le mail
            DateTime datNow = new DateTime();
            TimeSpan timeNow = new TimeSpan();
            datNow = DateTime.Now;
            timeNow = datNow.TimeOfDay;
            User user = new User();
            switch (datNow.DayOfWeek)
            {
                case DayOfWeek.Monday :
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(11).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(12).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(13).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;
                case DayOfWeek.Tuesday:
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(21).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(22).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(23).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;
                case DayOfWeek.Wednesday:
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(31).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(32).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(33).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;
                case DayOfWeek.Thursday:
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(41).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(42).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(43).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;
                case DayOfWeek.Friday :
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(51).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(52).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(53).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;
                case DayOfWeek.Saturday:
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(61).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(62).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(63).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;
                case DayOfWeek.Sunday:
                    if (timeNow.Hours < 8)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(71).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else if (timeNow.Hours < 16)
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(72).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    else
                    {
                        userId = ScheduleBLL.Instance.GetSchedule(73).user_id;
                        user = UserBLL.Instance.GetUser(userId);
                    }
                    break;

            }
            //Get conf mail
            Config confMail = ConfigBLL.Instance.GetConfigs()[0]; 

            // Mail message construction
            MailMessage mm = new MailMessage(confMail.conf_fn_mail, user.user_mail);
            
            // content
            mm.Subject = "Alerte OVS";
            mm.IsBodyHtml = true;
            string message1 = "Bonjour " + user.user_name;
            string message2 = "URGENT : Une alerte de level 1 a été détecté !!! Pour tous les détails sur cette alerte cliquez ";
            string hostName = "http://www.ovsproject.com/";
            string userName = user.user_login;
            string userPassword = user.user_pwd;

            // Update userID en BDD pour cette alerte
            if (userId > 0)
            {
                currentAlert.user_id = userId;
                AlertBLL.Instance.UpdateAlert(currentAlert);
            }


            bool authentificateInBase64 = true;

            if (authentificateInBase64)
            {
                userName = EncodeTo64(userName);
                userPassword = EncodeTo64(userPassword);
            }

            string messageLink = hostName + "Authenticate?userName=" + userName + "&password=" + userPassword + "&idAlerte=" + currentAlert.aler_id.ToString() + "&auto=" + authentificateInBase64.ToString().ToLower();

            mm.Body = @"<html> <head></head><body> " + message1 + ",<br/>" + message2+ "<a href=" + "\"" + messageLink + "\">ICI</a><br/><br/>  Cordialement,<br/>OVS<body></html>";

            // Sending message
            SmtpClient sc = new SmtpClient(confMail.conf_fn_serv, 587);

            // our account credentials
            sc.Credentials = new NetworkCredential(confMail.conf_fn_log, confMail.conf_fn_pwd, "");
            sc.EnableSsl = true;

            try
            {
                sc.Send(mm);
                _Log.Info("send mail ok");
            }
            catch (Exception ex)
            {
                _Log.Error("Error To send Mail: Msg: " + mm + " Exception: " + ex.Message);
            }

            try
            {               
                SMSSenderManager.Instance.sendSMSInThread(user.user_tel, message1 + ", " + "Alerte OVS" + ",  " + messageLink);
                _Log.Info("send sms ok");
            }
            catch (Exception ex)
            {
                _Log.Error("Error To send SMS:  Msg: " + mm + " Exception: " + ex.Message);
            }
        }
        /// <summary>
        /// Encodes the to Base64.
        /// </summary>
        /// <param name="toEncode">string to encode.</param>
        /// <returns></returns>
        private string EncodeTo64(string toEncode)
        {
            byte[] toEncodeAsBytes
                  = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
            string returnValue
                  = System.Convert.ToBase64String(toEncodeAsBytes);
            return returnValue;
        }
       
    }
    
}
